<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import {
  MEMBERSHIP_TYPES,
  MEMBERSHIP_PERMISSIONS,
  MEMBERSHIP_PLANS,
  NEW_USER_SPECIAL_OFFER,
  getUserPermissions,
  formatExpiryDate,
  getMembershipDisplayName
} from '../services/membershipService';

const router = useRouter();
const currentUser = ref({
  username: 'admin',
  membershipType: MEMBERSHIP_TYPES.NORMAL,
  membershipExpiry: null,
  isNewUser: true
});
const selectedTab = ref('info'); // info, upgrade
const selectedMembershipType = ref(MEMBERSHIP_TYPES.VIP);
const selectedPlan = ref(null);
const showSuccessModal = ref(false);

// 从本地存储获取用户信息（模拟）
onMounted(() => {
  const savedUser = localStorage.getItem('currentUser');
  if (savedUser) {
    currentUser.value = JSON.parse(savedUser);
  } else {
    // 模拟用户数据
    localStorage.setItem('currentUser', JSON.stringify(currentUser.value));
  }
});

// 获取用户权限信息
const userPermissions = computed(() => getUserPermissions(currentUser.value));

// 计算优惠信息
const calculateDiscount = (plan) => {
  const originalTotal = plan.originalPrice;
  const discount = originalTotal - plan.price;
  const discountPercent = Math.round((discount / originalTotal) * 100);
  return {
    discount,
    discountPercent,
    monthlyPrice: Math.round((plan.price / plan.period) * 100) / 100
  };
};

// 选择套餐
const selectPlan = (plan) => {
  selectedPlan.value = plan;
};

// 切换会员类型
const switchMembershipType = (type) => {
  selectedMembershipType.value = type;
  selectedPlan.value = null;
};

// 购买会员
const purchaseMembership = () => {
  if (!selectedPlan.value) {
    alert('请选择一个套餐');
    return;
  }
  
  // 检查是否是新人特惠
  let finalPrice = selectedPlan.value.price;
  let discountInfo = calculateDiscount(selectedPlan.value);
  
  if (currentUser.value.isNewUser && selectedPlan.value.duration === 'year') {
    if (selectedMembershipType.value === MEMBERSHIP_TYPES.VIP) {
      finalPrice = NEW_USER_SPECIAL_OFFER.vipYearly.price;
      discountInfo = {
        discount: NEW_USER_SPECIAL_OFFER.vipYearly.saving,
        discountPercent: NEW_USER_SPECIAL_OFFER.vipYearly.savingPercent,
        monthlyPrice: Math.round((finalPrice / 12) * 100) / 100
      };
    } else if (selectedMembershipType.value === MEMBERSHIP_TYPES.SUPER_VIP) {
      finalPrice = NEW_USER_SPECIAL_OFFER.superVipYearly.price;
      discountInfo = {
        discount: NEW_USER_SPECIAL_OFFER.superVipYearly.saving,
        discountPercent: NEW_USER_SPECIAL_OFFER.superVipYearly.savingPercent,
        monthlyPrice: Math.round((finalPrice / 12) * 100) / 100
      };
    }
  }
  
  // 模拟购买成功
  currentUser.value.membershipType = selectedMembershipType.value;
  currentUser.value.membershipExpiry = new Date();
  currentUser.value.membershipExpiry.setMonth(currentUser.value.membershipExpiry.getMonth() + selectedPlan.value.period);
  
  // 保存用户信息
  localStorage.setItem('currentUser', JSON.stringify(currentUser.value));
  
  // 显示成功弹窗
  showSuccessModal.value = true;
};

// 关闭成功弹窗
const closeSuccessModal = () => {
  showSuccessModal.value = false;
  selectedTab.value = 'info';
};

// 检查是否已选择该套餐
const isPlanSelected = (plan) => {
  return selectedPlan.value && selectedPlan.value.id === plan.id;
};

// 计算函数需要导入
import { computed } from 'vue';
</script>

<template>
  <div class="membership-center">
    <div class="container">
      <h1 class="page-title">会员中心</h1>
      
      <!-- 会员信息 -->
      <div class="membership-card" v-if="selectedTab === 'info'">
        <div class="membership-header">
          <div class="user-info">
            <h2>您好，{{ currentUser.username }}</h2>
            <div class="membership-status" :class="currentUser.membershipType">
              <span class="badge">{{ getMembershipDisplayName(currentUser.membershipType) }}</span>
              <span v-if="currentUser.membershipType !== MEMBERSHIP_TYPES.NORMAL" class="expiry">
                到期时间：{{ formatExpiryDate(currentUser.membershipExpiry) }}
              </span>
            </div>
          </div>
          <button 
            v-if="currentUser.membershipType === MEMBERSHIP_TYPES.NORMAL" 
            @click="selectedTab = 'upgrade'"
            class="upgrade-btn"
          >
            立即升级
          </button>
        </div>
        
        <div class="membership-permissions">
          <h3>您的权限</h3>
          <ul class="permissions-list">
            <li v-for="(feature, index) in userPermissions.features" :key="index">
              <span class="feature-icon">✓</span>
              {{ feature }}
            </li>
          </ul>
        </div>
        
        <div class="membership-limits" v-if="currentUser.membershipType !== MEMBERSHIP_TYPES.SUPER_VIP">
          <div class="limit-item">
            <span>每月最多查看作品：{{ userPermissions.limits.maxViewWorks }}</span>
          </div>
          <div class="limit-item">
            <span>每月最多联系次数：{{ userPermissions.limits.maxContactsPerMonth }}</span>
          </div>
          <div class="limit-item">
            <span>{{ userPermissions.limits.hasWatermark ? '作品带有水印' : '作品无水印' }}</span>
          </div>
          <div class="limit-item">
            <span>{{ userPermissions.limits.hasAds ? '显示广告' : '无广告体验' }}</span>
          </div>
        </div>
        
        <div class="upgrade-prompt" v-if="currentUser.membershipType !== MEMBERSHIP_TYPES.SUPER_VIP">
          <p>升级到 {{ currentUser.membershipType === MEMBERSHIP_TYPES.NORMAL ? 'VIP' : '超级VIP' }} 会员，享受更多特权！</p>
          <button @click="selectedTab = 'upgrade'" class="view-plans-btn">查看套餐</button>
        </div>
      </div>
      
      <!-- 会员升级 -->
      <div class="membership-upgrade" v-if="selectedTab === 'upgrade'">
        <div class="membership-type-selector">
          <button 
            @click="switchMembershipType(MEMBERSHIP_TYPES.VIP)"
            :class="['type-btn', { active: selectedMembershipType === MEMBERSHIP_TYPES.VIP }]"
          >
            <span class="badge vip">VIP</span>
            标准会员
          </button>
          <button 
            @click="switchMembershipType(MEMBERSHIP_TYPES.SUPER_VIP)"
            :class="['type-btn', { active: selectedMembershipType === MEMBERSHIP_TYPES.SUPER_VIP }]"
          >
            <span class="badge super-vip">SUPER VIP</span>
            超级会员
          </button>
        </div>
        
        <!-- 新人特惠提示 -->
        <div v-if="currentUser.isNewUser" class="new-user-banner">
          <span class="banner-icon">🎉</span>
          <span>新人专享特惠！首年购买立享超值优惠！</span>
        </div>
        
        <div class="plans-container">
          <div 
            v-for="plan in MEMBERSHIP_PLANS[selectedMembershipType]" 
            :key="plan.id"
            :class="['plan-card', { selected: isPlanSelected(plan) }]"
            @click="selectPlan(plan)"
          >
            <div class="plan-header">
              <h3>{{ plan.period }}个月</h3>
              <span class="plan-duration">{{ plan.durationText }}付</span>
            </div>
            
            <div class="plan-price">
              <span class="current-price">¥{{ plan.price }}</span>
              <span class="original-price">¥{{ plan.originalPrice }}</span>
              <span class="monthly-price">¥{{ Math.round((plan.price / plan.period) * 100) / 100 }}/月</span>
            </div>
            
            <!-- 新人特惠 -->
            <div v-if="currentUser.isNewUser && plan.duration === 'year'" class="new-user-discount">
              <div class="special-price">
                <span class="price-label">新人价：</span>
                <span class="price-value">¥{{ 
                  selectedMembershipType === MEMBERSHIP_TYPES.VIP 
                    ? NEW_USER_SPECIAL_OFFER.vipYearly.price 
                    : NEW_USER_SPECIAL_OFFER.superVipYearly.price 
                }}</span>
              </div>
              <div class="saving-info">
                <span class="saving-amount">
                  省¥{{ 
                    selectedMembershipType === MEMBERSHIP_TYPES.VIP 
                      ? NEW_USER_SPECIAL_OFFER.vipYearly.saving 
                      : NEW_USER_SPECIAL_OFFER.superVipYearly.saving 
                  }}
                </span>
                <span class="saving-percent">
                  ({{ 
                    selectedMembershipType === MEMBERSHIP_TYPES.VIP 
                      ? NEW_USER_SPECIAL_OFFER.vipYearly.savingPercent 
                      : NEW_USER_SPECIAL_OFFER.superVipYearly.savingPercent 
                  }}%OFF)
                </span>
              </div>
            </div>
            
            <div class="plan-discount" v-else>
              <span class="discount-tag">
                省{{ calculateDiscount(plan).discountPercent }}%
              </span>
              <span class="discount-text">{{ plan.discountText }}</span>
            </div>
            
            <div class="plan-features">
              <h4>包含权益：</h4>
              <ul>
                <li v-for="(feature, index) in MEMBERSHIP_PERMISSIONS[selectedMembershipType].features.slice(0, 4)" :key="index">
                  <span class="feature-icon">✓</span>
                  {{ feature }}
                </li>
                <li v-if="MEMBERSHIP_PERMISSIONS[selectedMembershipType].features.length > 4">
                  <span class="feature-icon">✓</span>
                  更多{{ MEMBERSHIP_PERMISSIONS[selectedMembershipType].features.length - 4 }}项权益...
                </li>
              </ul>
            </div>
            
            <div class="plan-selector">
              <div class="checkbox" :class="{ checked: isPlanSelected(plan) }">
                <span v-if="isPlanSelected(plan)" class="check-icon">✓</span>
              </div>
              <span>选择</span>
            </div>
          </div>
        </div>
        
        <!-- 立即购买 -->
        <div class="purchase-section">
          <div class="purchase-summary">
            <div v-if="selectedPlan" class="summary-details">
              <span>选择套餐：{{ selectedPlan.period }}个月{{ selectedPlan.durationText }}付</span>
              <span v-if="currentUser.isNewUser && selectedPlan.duration === 'year'" class="new-user-price-tag">
                新人价：¥{{ 
                  selectedMembershipType === MEMBERSHIP_TYPES.VIP 
                    ? NEW_USER_SPECIAL_OFFER.vipYearly.price 
                    : NEW_USER_SPECIAL_OFFER.superVipYearly.price 
                }}
              </span>
              <span v-else class="regular-price-tag">
                总价：¥{{ selectedPlan.price }}
              </span>
            </div>
            <span v-else class="no-selection">请选择一个套餐</span>
          </div>
          <button 
            @click="purchaseMembership" 
            :disabled="!selectedPlan"
            class="purchase-btn"
          >
            立即购买
          </button>
        </div>
      </div>
      
      <!-- 返回按钮 -->
      <button @click="router.push('/')" class="back-btn">返回首页</button>
    </div>
    
    <!-- 成功弹窗 -->
    <div v-if="showSuccessModal" class="modal-overlay" @click.self="closeSuccessModal">
      <div class="success-modal">
        <div class="modal-header">
          <h3>购买成功！</h3>
        </div>
        <div class="modal-body">
          <div class="success-icon">✓</div>
          <p>恭喜您成功升级为{{ getMembershipDisplayName(selectedMembershipType) }}！</p>
          <p class="expiry-info">会员有效期：{{ formatExpiryDate(currentUser.membershipExpiry) }}</p>
        </div>
        <div class="modal-footer">
          <button @click="closeSuccessModal" class="confirm-btn">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.membership-center {
  padding: 40px 0;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  text-align: center;
  font-size: 32px;
  margin-bottom: 40px;
  color: #333;
}

/* 会员卡片样式 */
.membership-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.membership-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e8e8e8;
}

.user-info h2 {
  font-size: 24px;
  margin-bottom: 10px;
  color: #333;
}

.membership-status {
  display: flex;
  align-items: center;
  gap: 15px;
}

.badge {
  padding: 5px 15px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: bold;
}

.badge.normal {
  background-color: #e0e0e0;
  color: #666;
}

.badge.vip {
  background-color: #ffd700;
  color: #333;
}

.badge.super-vip {
  background: linear-gradient(45deg, #ff6b6b, #ffa502);
  color: white;
}

.expiry {
  font-size: 14px;
  color: #666;
}

.upgrade-btn {
  padding: 10px 30px;
  background-color: #ff6b6b;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.upgrade-btn:hover {
  background-color: #ff5252;
  transform: translateY(-2px);
}

/* 权限列表 */
.membership-permissions {
  margin-bottom: 30px;
}

.membership-permissions h3 {
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
}

.permissions-list {
  list-style: none;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.permissions-list li {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  font-size: 15px;
  color: #666;
}

.feature-icon {
  color: #4CAF50;
  font-weight: bold;
  min-width: 20px;
  text-align: center;
}

/* 限制说明 */
.membership-limits {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.limit-item {
  margin-bottom: 10px;
  color: #666;
}

.limit-item:last-child {
  margin-bottom: 0;
}

/* 升级提示 */
.upgrade-prompt {
  text-align: center;
  padding: 20px;
  background-color: #fff3cd;
  border-radius: 8px;
  border: 1px solid #ffeaa7;
}

.upgrade-prompt p {
  margin-bottom: 15px;
  color: #856404;
}

.view-plans-btn {
  padding: 10px 30px;
  background-color: #ff6b6b;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.view-plans-btn:hover {
  background-color: #ff5252;
}

/* 会员升级页面 */
.membership-upgrade {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.membership-type-selector {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 30px;
}

.type-btn {
  padding: 15px 40px;
  border: 2px solid #e0e0e0;
  background-color: white;
  border-radius: 8px;
  font-size: 18px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 10px;
}

.type-btn.active {
  border-color: #ff6b6b;
  background-color: #fff5f5;
}

.type-btn:hover:not(.active) {
  border-color: #ff6b6b;
}

/* 新人特惠横幅 */
.new-user-banner {
  background: linear-gradient(135deg, #ff6b6b, #ffa502);
  color: white;
  padding: 15px;
  border-radius: 8px;
  text-align: center;
  margin-bottom: 30px;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.banner-icon {
  font-size: 24px;
}

/* 套餐容器 */
.plans-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 30px;
  margin-bottom: 40px;
}

.plan-card {
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  padding: 30px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.plan-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
}

.plan-card.selected {
  border-color: #ff6b6b;
  background-color: #fff5f5;
}

.plan-header {
  text-align: center;
  margin-bottom: 20px;
}

.plan-header h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 5px;
}

.plan-duration {
  color: #666;
  font-size: 14px;
}

/* 价格样式 */
.plan-price {
  text-align: center;
  margin-bottom: 20px;
}

.current-price {
  font-size: 36px;
  font-weight: bold;
  color: #ff6b6b;
  margin-right: 10px;
}

.original-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
  margin-right: 10px;
}

.monthly-price {
  font-size: 14px;
  color: #666;
}

/* 新人特惠 */
.new-user-discount {
  background-color: #ff6b6b;
  color: white;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  text-align: center;
}

.special-price {
  margin-bottom: 10px;
  font-size: 18px;
}

.price-label {
  font-size: 16px;
}

.price-value {
  font-size: 28px;
  font-weight: bold;
}

.saving-info {
  font-size: 14px;
}

.saving-amount {
  font-weight: bold;
  margin-right: 10px;
}

.saving-percent {
  background-color: white;
  color: #ff6b6b;
  padding: 2px 8px;
  border-radius: 10px;
  font-weight: bold;
}

/* 普通优惠 */
.plan-discount {
  text-align: center;
  margin-bottom: 20px;
}

.discount-tag {
  background-color: #ff6b6b;
  color: white;
  padding: 5px 15px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: bold;
  margin-right: 10px;
}

.discount-text {
  color: #666;
  font-size: 14px;
}

/* 权益列表 */
.plan-features {
  margin-bottom: 20px;
}

.plan-features h4 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
}

.plan-features ul {
  list-style: none;
}

.plan-features li {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

/* 选择器 */
.plan-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.checkbox {
  width: 20px;
  height: 20px;
  border: 2px solid #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox.checked {
  background-color: #ff6b6b;
  border-color: #ff6b6b;
}

.check-icon {
  color: white;
  font-size: 14px;
  font-weight: bold;
}

/* 购买区域 */
.purchase-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.summary-details {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.new-user-price-tag {
  color: #ff6b6b;
  font-weight: bold;
  font-size: 18px;
}

.regular-price-tag {
  color: #333;
  font-weight: bold;
  font-size: 18px;
}

.no-selection {
  color: #999;
}

.purchase-btn {
  padding: 15px 40px;
  background-color: #ff6b6b;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
}

.purchase-btn:hover:not(:disabled) {
  background-color: #ff5252;
  transform: translateY(-2px);
}

.purchase-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 返回按钮 */
.back-btn {
  margin-top: 30px;
  padding: 10px 30px;
  background-color: #666;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: #555;
}

/* 成功弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.success-modal {
  background-color: white;
  border-radius: 12px;
  padding: 30px;
  max-width: 500px;
  width: 90%;
  text-align: center;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
}

.modal-header h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

.success-icon {
  width: 80px;
  height: 80px;
  background-color: #4CAF50;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48px;
  margin: 0 auto 20px;
}

.modal-body p {
  font-size: 18px;
  color: #666;
  margin-bottom: 10px;
}

.expiry-info {
  font-size: 16px;
  color: #999;
  margin-bottom: 30px;
}

.confirm-btn {
  padding: 12px 40px;
  background-color: #ff6b6b;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.confirm-btn:hover {
  background-color: #ff5252;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .membership-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }
  
  .plans-container {
    grid-template-columns: 1fr;
  }
  
  .purchase-section {
    flex-direction: column;
    gap: 20px;
  }
  
  .membership-type-selector {
    flex-direction: column;
  }
  
  .type-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>